package com.example.net1;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ReceiptHtmlAdapter {

	private Receipt receipt;
	private long nonce;
	
	public ReceiptHtmlAdapter(Receipt receipt, long nonce) {
		this.receipt = receipt;
		this.nonce = nonce;
	}
	
	public void write(File file) {
		FileOutputStream f;
		PrintWriter pw = null;
		try {
			DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			Date date = new Date();
			f = new FileOutputStream(file);
			pw = new PrintWriter(f);
			pw.write("<html><body><TABLE BORDER=\"1\"> ");
			pw.write("<caption>Receipt #" + nonce + " - " + dateFormat.format(date) + "</caption>");
			pw.write("<tr><th>Item</th><th>Unit price</th><th>#</th><th>Price</th></tr>");
			for (Item item : receipt.items) {
				pw.write("<tr>" +
						"<td>" + item.description + "</td>" +
						"<td>" + item.price + "</td>" +
						"<td>" + item.number + "</td>" +
						"<td>" + (item.number*item.price) + "</td>" +
						"</tr>");
				
			}
			pw.write("</body></html>");
			pw.flush();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			pw.close();
		}
	}
	
}
